<?php
    /*

     Version: MPL 1.1

     Software distributed under the License is distributed on an "AS IS"
     basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
     License for the specific language governing rights and limitations
     under the License.

     The Original Code is KASSIOP Framework.

     The Initial Developer of the Original Code is SURIAN Nicolas (aka NairuS) <me@nairus.fr>.
     Portions created by the Initial Developer are Copyright (C) 2010
     The Initial Developer. All Rights Reserved.

     Contributor(s):

     Alternatively, the contents of this file may be used under the terms
     of the MPL license Version 1.1 (the  "MPL" License"), in which case the
     provisions of Version: MPL 1.1 License are applicable instead of those
     above.  If you wish to allow use of your version of this file only
     under the terms of the MPL License and not to allow others to use
     your version of this file under the MPL, indicate your decision by
     deleting  the provisions above and replace  them with the notice and
     other provisions required by the MPL License.  If you do not delete
     the provisions above, a recipient may use your version of this file
     under either the MPL License.

     The contents of this file are subject to the Mozilla Public License
     Version 1.1 (the "License"); you may not use this file except in
     compliance with the License. You may obtain a copy of the License at
     http://www.mozilla.org/MPL/

    */

    /**
     * The media backend service.
     *
     * @package    applications.services
     * @subpackage backend
     *
     * @author NairuS
     * @version 1.3 $Rev: 90 $ $Date: 2011-01-16 09:23:26 +0000 (Sun, 16 Jan 2011) $ $Author: nicolas.surian $
     */
    class MediaBackendService extends ServicesAdmin
    {
        /**
         * Create an instance of MediaBackendService
         *
         * @param string $file initialize an other mysql configuration.
         */
        public function __construct( $file = null )
        {
            parent::__construct($file);
            $this->table = '`kp_media`';
        }

        /**
         * Deletes an object form the model with the id passed-in.
         *
         * @param mixed $id integer or string identifier of the object.
         * @return boolean  True if the object has been deleted, false otherwise.
         */
        public function delete( $id )
        {
            $query = "DELETE FROM " . $this->table . " WHERE " . $this->table . ".`id` = '" . $this->sanitize( $id ) . "';" ;
            return $this->getResult( $query ) ;
        }

        /**
         * Return the MediaVO for the id passed-in.
         *
         * @param  mixed       $id integer or string identifier of the object.
         * @return ValueObject
         */
        public function find( $id )
        {
            $query  = "SELECT * FROM " . $this->table . " WHERE " . $this->table . ".`id` = '" . $this->sanitize( $id ) . "'" ;
            $result = $this->getResult( $query ) ;
            return $this->getVO( mysql_fetch_array( $result ) ) ;
        }

        /**
         * Return an array of MediaVO.
         *
         * @param  array  $conditions     defines the where conditions of the query.
         * @param  array  $orders         defines the orderBy conditions of the query.
         * @param  string $orderDirection defines the orderBy direction of the query.
         * @return array                  of MediaVO.
         */
        public function findAll( $conditions = array(), $orders = array(), $orderDirection = ServicesMysql::ASC )
        {
            $where   = empty( $conditions ) ? null : $this->buildWhere( $conditions ) ;
            $orderBy = empty( $orders )     ? null : $this->buildOrderBy( $orders, $orderDirection );
            $query   = "SELECT * FROM " . $this->table . $where . $orderBy . ";" ;
            $result  = $this->getResult( $query ) ;

             $stack = array() ;
            if( mysql_num_rows($result) > 0 )
            {
                while( $row = mysql_fetch_array( $result ) )
                {
                    array_push( $stack, $this->getVO( $row ) ) ;
                }
            }
            return $stack ;
        }

        /**
         * Add a new MediaVO in the db.
         *
         * @param  array $values
         * @return mixed         True if the object has been inserted, ErrorsModelVO otherwise.
         */
        public function insert( $values )
        {
            $model = new MediaModel( $this->getVO( $values ) );

            $sql    = 'INSERT INTO ' . $this->table . " (`label`, `endAt`, `file`, `startAt`) VALUES('{label}', '{endAt}', '" . $this->cleanFileValue( $model ) . "', '{startAt}');" ;
            $result = $this->validate( $model, $sql );
            return $result === true ? $this->connect->getLastID() : $result ;
        }

        /**
         * Update the object in the db.
         *
         * @param  array $values
         * @return mixed          True if the object has been inserted, ErrorsModelVO otherwise.
         */
        public function update( $values )
        {
            $model = new MediaModel( $this->getVO( $values ) );

            $sql = 'UPDATE ' . $this->table . " SET
                    " . $this->table . ".`label` = '{label}',
                    " . $this->table . ".`endAt` = '{endAt}',
                    " . $this->table . ".`file` = '" . $this->cleanFileValue( $model ) . "',
                    " . $this->table . ".`startAt` = '{startAt}' " .
                    "WHERE " . $this->table . ".`id` = '{id}';" ;
            return $this->validate($model, $sql);
        }

        /**
         * Returns the MediaVO of a result query row.
         *
         * @param  array       A row datas from the database to format in MediaVO.
         * @return MediaVO     of a result query row.
         */
        protected function getVO( array $row )
        {
            return new MediaVO( $row );
        }

        /**
         * Clean the file value field according the context.
         *
         * @param  MediaModel $model The reference of the model to validate.
         * @return void
         */
        private function cleanFileValue( MediaModel &$model )
        {
            // if this is an upload file array
            if( is_array( $model->getVO()->file ) )
            {
                $fileValue = '{file}';
            }
            else
            {
                $fileValue = $model->getVO()->file ;
                $model->getVO()->file = null;
            }
            return $fileValue;
        }
    }
?>